<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Cache;
use think\Db;
use think\Env;
use think\Hook;
use think\Log;

class MiniApp extends Api{

    protected $noNeedLogin = ['login','testLogin','test','login2','getmobile'];
    protected $noNeedRight = ['*'];

    protected $model;
    protected $config;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\MiniApp();
        $this->config = $this->model->getMiniAppConfig();
    }

    public function test()
    {
        $app = Factory::miniProgram($this->config);

        $decryptedData = $app->encryptor->decryptData(123, 689, 456);
    }

    //小程序登录
    public function login(){

        $code = $this->request->param('code','');
        $pid = $this->request->param('pid','0');
        $userInfo=[];
        Log::write('params:'.json_encode($this->request->param()),'info');

        if(empty($code)){
            $this->error('缺少code参数！');
        }

        try {
            // 调用微信接口，获取用户微信开放信息
            $app = Factory::miniProgram($this->config);
            $wx_res = $app->auth->session($code);
            Log::info("sessionData:".json_encode($wx_res));
        } catch (DecryptException $e) {
            $this->error('请刷新后重新授权登录', '', 415);
        }

        if (!$wx_res) {
            return json(['code'=>400, 'msg'=>'获取小程序用户信息失败！']);
        }
        if(empty($wx_res['openid'])){
            return json(['code'=>400, 'msg'=>'errcode->'.$wx_res['errcode'].';errmsg->'.$wx_res['errmsg']]);
        }

        //微信用戶信息
//        $user_info = $this->request->param('user_info','');
//        if ($user_info) {
//            $user_arr = htmlspecialchars_decode($user_info);
//            $user_info = json_decode($user_arr, true);
//        }

//        //获取手机号码
//        $iv = $this->request->param('iv','');
//        !$iv && $this->error('缺少iv参数！');
//        $encryptedData  = $this->request->param('encryptedData','');
//        !$encryptedData && $this->error('缺少encryptedData参数！');
//        $mobileRes = $this->getPhone($iv,$encryptedData,$wx_res['session_key']);
////        $mobileRes = ['result' => '123456789','code' => '200'];
//        if($mobileRes['code'] == 400){
//            $this->error($mobileRes['msg']);
//        }
        //上线测试使用
//        if($mobileRes['result'] != '15217569160'){
//            $this->error('系统升级中');
//        }
        try {
            if( empty($wx_res)){
                $this->error('沒有获取到用户信息！');
            }

            //判断是否存在用户
//            $user = \app\common\model\User::where('mobile', $mobileRes['result'])->find();
            $user = \app\common\model\User::where('openid',$wx_res['openid'])->find();

            if (isset($user['mobile']) && $user['mobile'] >1) {
                //存在，更新数据
                $ip = request()->ip();
//                $fields = [
//                    'openid'        => $wx_res['openid'],
//                    'session_key'   => $wx_res['session_key'],
////                    'nickname'      => $user_info['nickName'],
////                    'avatar'        => $user_info['avatarUrl'],
//                    'loginip'       => $ip,
//                ];
                if($user['status'] == '0'){
                    $this->error('该用户已被禁用');
                }
//                $user->save($fields);
                $user_id = \app\common\model\User::where('openid',$wx_res['openid'])->value('id');


//                $this->success('success',$wx_res['openid'],'');
                $ret = $this->auth->direct($user_id);
            } else{
                if (!$user)
                {

                    $ret = $this->auth->register($wx_res['openid'],$wx_res['session_key'],$pid,'');
                }
                $this->success('success',['type'=>0,'data'=>$wx_res['openid']]);
//                $this->error('用户不存在','',401);
            }
            //用户登录成功
//            Hook::listen('user_login_after',$user_id);
            if ($ret) {
                $userInfo = $this->auth->getUserinfo();
                $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                $userInfo['openid'] = $wx_res['openid'];
                $this->success('登录成功！',['type'=>1,'data'=>$userInfo]);
            } else {
                $this->error('登录失败');
            }

        }
        catch (\think\exception\PDOException $e)
        {
            $this->error($e->getMessage());
        }
    }
    public function login2()
    {
        $openid = $this->request->param('openid','');
        $mobile = $this->request->param('mobile','');
        $nickname= $this->request->param('nickname','');
        $avatarUrl = $this->request->param('avatarUrl','');
        $user = Db::name('user')->where('openid',$openid)->find();


        if (!$openid)
        {
            $this->error('缺少openid');
        }
        if (!$mobile)
        {
            $this->error('缺少手机号');
        }
        if ($user)
        {

            if ($user['mobile'])
            {

                if ($user['mobile'] == $mobile)
                {
                    Db::name('user')->where('id',$user['id'])->update(['nickname'=>$nickname,'avatar'=>$avatarUrl]);

                    $ret = $this->auth->direct($user['id']);
                    if ($ret) {
                        $userInfo = $this->auth->getUserinfo();
                        $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                        $this->success('登录成功1！',$userInfo);
                    } else {
                        $this->error('登录失败');
                    }
                }else{
                    Db::name('user')->where('openid',$openid)->update(['mobile'=>$mobile,'nickname'=>$nickname,'avatar'=>$avatarUrl]);
                    $ret = $this->auth->direct($user['id']);
                    if ($ret) {
                        $userInfo = $this->auth->getUserinfo();
                        $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                        $this->success('登录成功2！',$userInfo);
                    } else {
                        $this->error('登录失败');
                    }
                }
            }else{
                Db::name('user')->where('openid',$openid)->update(['mobile'=>$mobile,'nickname'=>$nickname,'avatar'=>$avatarUrl]);

                $ret = $this->auth->direct($user['id']);
                if ($ret) {
                    $userInfo = $this->auth->getUserinfo();
                    $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                    $this->success('登录成功2！',$userInfo);
                } else {
                    $this->error('登录失败');
                }
            }
        }else{
            $ret = $this->auth->register($openid,'','0',$mobile);
            if ($ret) {
                $userInfo = $this->auth->getUserinfo();
                $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
                $this->success('注册成功！',$userInfo);
            } else {
                $this->error('注册失败');
            }
        }
    }
    public function getmobile()
    {
        $code = $this->request->post('code');
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$accessToken}";
        $data = ['code'=>$code];
        $result = curl_post($url,json_encode($data));
//        halt(json_decode($result,true));
        Log::record('手机号验证',$result);
        $this->success('获取成功',json_decode($result,true));
////
//        $app = Factory::miniProgram($this->config);
//        $result = $app->phone_number->getUserPhoneNumber($code);
    }

    public function getAccessToken(){
//        if(Cache::get('accessToken')){
//            return Cache::get('accessToken');
//        }
           $appid  = Env::get('wxconfig.app_id', '');
           $secret =  Env::get('wxconfig.secret', '');
//        $url="https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=ACCESS_TOKEN";
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $a=$this->curl_get($url);

        $a=json_decode($a,true);
        Cache::set('accessToken',$a['access_token'],$a['expires_in']);
        return $a['access_token'];
    }
    public function getAccessToken1() {
        // access_token 应该全局存储与更新
        // 获取数据库中的access_token
        $token = Cache::get('access_token');
        $appid  = Env::get('wxconfig.app_id', '');
        $secret =  Env::get('wxconfig.secret', '');
//        halt($token);
        // accessToken过期或不存在时
        if(!$token){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
            // 微信返回的信息

            $returnData = json_decode($this->curl_get($url));
            // 组装数据
            $resData['accessToken'] = $returnData->access_token;
            $resData['expiresIn'] = $returnData->expires_in;
            $resData['time'] = date("Y-m-d H:i",time());
            //
            Cache::set('access_token',$returnData->access_token,7200);
            $res = Cache::get('access_token');
        }else{
            $res = $token;
        }
        return $res;
    }


    /***
     * get请求
     * @param $url
     * @param int $httpCode
     * @return bool|string
     */
    function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

    //获取手机号
    public function getPhone($iv,$encryptedData,$sessionKey)
    {
        if(empty($iv)){
            return ['code'=>400, 'msg'=>'缺少iv参数！'];
        }
        if(empty($encryptedData)){
            return ['code'=>400, 'msg'=>'缺少encryptedData参数！'];
        }

        $app = Factory::miniProgram($this->config);

        $decryptedData = $app->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        if (empty($decryptedData['phoneNumber'])) {
            return ['code'=>400, 'msg'=>'获取手机号失败！'];
        }
        try
        {
            return ['code'=>200, 'msg'=>'保存手机号成功。','result'=>$decryptedData['phoneNumber']];
        }
        catch (\think\exception\PDOException $e)
        {
            return ['code'=>400, 'msg'=>$e->getMessage()];
        }
    }


    //模拟登录
    public function testLogin(){
        $openid = $this->request->param('openid','');


        try {
            //模拟数据
            $wx_res = ['openid'=>$openid,'session_key'=>1];
            //判断是否存在用户
            $user = \app\common\model\User::where('openid', $wx_res['openid'])->find();

            if ($user) {

            } else{
                $this->error('用户未获得授权，无法登录','',401);


            }
            $ret = $this->auth->direct($user->id);

            //用户登录成功
            $userId = $user->id;

            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error('登录失败！');
            }
        }
        catch (\think\exception\PDOException $e)
        {
            $this->error($e->getMessage());
        }
    }


}